<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Lock, Camera, Edit, Loading } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import type { User as UserType } from '@/types/user'

const userStore = useUserStore()

// 用户信息表单
const userForm = reactive<{
  username: string
  email: string
  phonenumber: string
  avatar: string
  nickname: string
  gender: string
  birthday: Date | string
  bio: string
}>({
  username: '',
  email: '',
  phonenumber: '',
  avatar: '',
  nickname: '',
  gender: '',
  birthday: '',
  bio: ''
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单引用
const userFormRef = ref()
const passwordFormRef = ref()

// 加载状态
const loading = ref(false)
const passwordLoading = ref(false)

// 头像上传
const avatarUrl = ref('')
const uploadLoading = ref(false)

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phonenumber: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 初始化用户信息
const initUserInfo = async () => {
  // 首先尝试从store获取用户信息
  let user = userStore.user
  
  // 如果store中没有用户信息，或者用户信息不完整，则重新获取
  if (!user || user.nickname === undefined) {
    try {
      console.log('重新获取用户信息...')
      user = await userStore.fetchUserInfo()
      console.log('获取到的用户信息:', user)
    } catch (error) {
      console.error('获取用户信息失败:', error)
      ElMessage.error('获取用户信息失败，请刷新页面重试')
      return
    }
  }
  
  if (user) {
    console.log('初始化表单数据:', {
      nickname: user.nickname,
      gender: user.gender,
      birthday: user.birthday,
      bio: user.bio
    })
    
    // 处理生日数据，将字符串转换为Date对象
    let birthdayDate: Date | string = ''
    if (user.birthday && typeof user.birthday === 'string') {
      try {
        birthdayDate = new Date(user.birthday + 'T00:00:00')
      } catch (error) {
        console.error('日期转换失败:', error)
        birthdayDate = ''
      }
    } else {
      birthdayDate = user.birthday || ''
    }
    
    Object.assign(userForm, {
      username: user.username || '',
      email: user.email || '',
      phonenumber: user.phonenumber || '',
      avatar: user.avatar || '',
      nickname: user.nickname || '',
      gender: user.gender || '',
      birthday: birthdayDate,
      bio: user.bio || ''
    })
    // 直接使用相对URL，Vite代理会处理路由
    avatarUrl.value = user.avatar || ''
    
    console.log('表单数据初始化完成:', userForm)
  }
}

// 保存用户信息
const saveUserInfo = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    loading.value = true
    
    // 处理生日格式，确保是字符串格式
    let birthdayStr: string | undefined = undefined
    if (userForm.birthday) {
      if (userForm.birthday instanceof Date) {
        // 如果是Date对象，转换为YYYY-MM-DD格式
        birthdayStr = userForm.birthday.toISOString().split('T')[0]
      } else if (typeof userForm.birthday === 'string') {
        // 如果已经是字符串，直接使用
        birthdayStr = userForm.birthday
      }
    }
    
    console.log('发送的数据:', {
      email: userForm.email,
      phonenumber: userForm.phonenumber,
      nickname: userForm.nickname,
      gender: userForm.gender,
      birthday: birthdayStr,
      bio: userForm.bio
    })
    
    // 调用API更新用户信息
    const result = await userStore.updateProfile({
      email: userForm.email,
      phonenumber: userForm.phonenumber,
      nickname: userForm.nickname,
      gender: userForm.gender,
      birthday: birthdayStr,
      bio: userForm.bio
    })
    
    if (result.success) {
      ElMessage.success(result.message)
      // 更新成功后重新初始化表单数据，确保显示最新数据
      await initUserInfo()
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败，请重试')
  } finally {
    loading.value = false
  }
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    // 调用API修改密码
    const result = await userStore.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })
    
    if (result.success) {
      ElMessage.success(result.message)
      
      // 清空表单
      Object.assign(passwordForm, {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error('密码修改失败，请重试')
  } finally {
    passwordLoading.value = false
  }
}

// 头像上传处理
const handleAvatarUpload = async (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像大小不能超过 2MB!')
    return false
  }

  uploadLoading.value = true
  
  try {
    // 调用API上传头像
    const result = await userStore.uploadAvatar(file)
    
    if (result.success && result.avatar) {
      // 直接使用相对URL，Vite代理会处理路由
      avatarUrl.value = result.avatar
      userForm.avatar = result.avatar
      ElMessage.success(result.message)
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
  } finally {
    uploadLoading.value = false
  }

  return false // 阻止自动上传
}

onMounted(() => {
  initUserInfo()
})
</script>

<template>
  <div class="profile-container">
    <div class="profile-header">
      <div class="header-bg"></div>
      <div class="user-avatar-section">
        <el-upload
          :show-file-list="false"
          :before-upload="handleAvatarUpload"
          class="avatar-uploader"
        >
          <div class="avatar-wrapper">
            <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
            <el-icon v-else class="avatar-placeholder"><User /></el-icon>
            <div class="avatar-overlay">
              <el-icon><Camera /></el-icon>
              <span>更换头像</span>
            </div>
            <div v-if="uploadLoading" class="avatar-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
            </div>
          </div>
        </el-upload>
        <div class="user-info">
          <h2 class="username">{{ userForm.nickname || userForm.username }}</h2>
          <p class="user-bio">{{ userForm.bio || '暂无个人简介' }}</p>
        </div>
      </div>
    </div>

    <div class="profile-content">
      <el-row :gutter="24">
        <!-- 个人信息编辑 -->
        <el-col :lg="14" :md="24">
          <el-card class="info-card">
            <template #header>
              <div class="card-header">
                <el-icon><Edit /></el-icon>
                <span>个人信息</span>
              </div>
            </template>
            
            <el-form
              ref="userFormRef"
              :model="userForm"
              :rules="userRules"
              label-width="100px"
              label-position="left"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" :disabled="true" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email" placeholder="请输入邮箱" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phonenumber">
                    <el-input v-model="userForm.phonenumber" placeholder="请输入手机号" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="性别">
                    <el-radio-group v-model="userForm.gender">
                      <el-radio value="male">男</el-radio>
                      <el-radio value="female">女</el-radio>
                      <el-radio value="other">其他</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生日">
                    <el-date-picker
                      v-model="userForm.birthday"
                      type="date"
                      placeholder="请选择生日"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="个人简介">
                <el-input
                  v-model="userForm.bio"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入个人简介"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  size="large"
                  :loading="loading"
                  @click="saveUserInfo"
                >
                  保存信息
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 密码修改 -->
        <el-col :lg="10" :md="24">
          <el-card class="password-card">
            <template #header>
              <div class="card-header">
                <el-icon><Lock /></el-icon>
                <span>修改密码</span>
              </div>
            </template>
            
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="80px"
            >
              <el-form-item label="当前密码" prop="oldPassword">
                <el-input
                  v-model="passwordForm.oldPassword"
                  type="password"
                  placeholder="请输入当前密码"
                  show-password
                />
              </el-form-item>

              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="请输入新密码"
                  show-password
                />
              </el-form-item>

              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请确认新密码"
                  show-password
                />
              </el-form-item>

              <el-form-item>
                <el-button
                  type="danger"
                  size="large"
                  :loading="passwordLoading"
                  @click="changePassword"
                  style="width: 100%"
                >
                  修改密码
                </el-button>
              </el-form-item>
            </el-form>

            <!-- 安全提示 -->
            <el-alert
              title="安全提示"
              type="info"
              :closable="false"
              show-icon
            >
              <template #default>
                <ul class="security-tips">
                  <li>密码长度至少6位字符</li>
                  <li>建议包含数字、字母和特殊字符</li>
                  <li>定期更换密码确保账户安全</li>
                </ul>
              </template>
            </el-alert>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped lang="scss">
.profile-container {
  padding: 24px;
  background: transparent;
  min-height: calc(100vh - 64px);
  
  .profile-header {
    position: relative;
    margin-bottom: 32px;
    
    .header-bg {
      height: 200px;
      background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
      border-radius: 16px;
      position: relative;
      overflow: hidden;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: radial-gradient(circle at 30% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
                    radial-gradient(circle at 70% 80%, rgba(255, 255, 255, 0.08) 0%, transparent 50%);
      }
    }
    
    .user-avatar-section {
      position: absolute;
      bottom: -60px;
      left: 40px;
      display: flex;
      align-items: flex-end;
      gap: 24px;
      
      .avatar-uploader {
        .avatar-wrapper {
          position: relative;
          width: 120px;
          height: 120px;
          border-radius: 16px;
          overflow: hidden;
          border: 4px solid white;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
          cursor: pointer;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
            
            .avatar-overlay {
              opacity: 1;
            }
          }
          
          .avatar,
          .avatar-placeholder {
            width: 100%;
            height: 100%;
            object-fit: cover;
            background: #f8fafc;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 40px;
            color: #cbd5e1;
          }
          
          .avatar-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.6);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: white;
            opacity: 0;
            transition: opacity 0.3s ease;
            
            .el-icon {
              font-size: 24px;
              margin-bottom: 8px;
            }
            
            span {
              font-size: 12px;
              font-weight: 500;
            }
          }
          
          .avatar-loading {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            
            .el-icon {
              font-size: 24px;
              color: #3b82f6;
            }
          }
        }
      }
      
      .user-info {
        margin-bottom: 20px;
        
        .username {
          font-size: 32px;
          font-weight: 700;
          color: #1e293b;
          margin: 0 0 8px 0;
          text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          letter-spacing: -0.025em;
        }
        
        .user-bio {
          color: #64748b;
          font-size: 16px;
          margin: 0;
          max-width: 400px;
          line-height: 1.5;
        }
      }
    }
  }
  
  .profile-content {
    margin-top: 80px;
    
    .el-card {
      border-radius: 16px;
      border: 1px solid rgba(226, 232, 240, 0.8);
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 20px rgba(0, 0, 0, 0.04);
      overflow: hidden;
      
      :deep(.el-card__header) {
        background: #f8fafc;
        border-bottom: 1px solid #e2e8f0;
        padding: 24px;
        
        .card-header {
          display: flex;
          align-items: center;
          gap: 12px;
          font-weight: 600;
          color: #1e293b;
          font-size: 18px;
          
          .el-icon {
            font-size: 20px;
            color: #3b82f6;
          }
        }
      }

      :deep(.el-card__body) {
        padding: 32px;
      }
    }
    
    .info-card {
      margin-bottom: 24px;
      
      .el-form {
        .el-form-item {
          margin-bottom: 28px;

          :deep(.el-form-item__label) {
            font-weight: 600;
            color: #374151;
            margin-bottom: 8px;
            font-size: 14px;
          }
        }
        
        .el-input,
        .el-date-picker,
        .el-textarea {
          :deep(.el-input__wrapper) {
            border-radius: 8px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
            border: 1px solid #d1d5db;
            transition: all 0.3s ease;
            
            &:hover {
              border-color: #9ca3af;
            }
            
            &.is-focus {
              border-color: #3b82f6;
              box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            }

            .el-input__inner {
              &::placeholder {
                color: #9ca3af;
              }
            }
          }
        }

        .el-textarea {
          :deep(.el-textarea__inner) {
            border-radius: 8px;
            border: 1px solid #d1d5db;
            transition: all 0.3s ease;
            
            &:hover {
              border-color: #9ca3af;
            }
            
            &:focus {
              border-color: #3b82f6;
              box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            }

            &::placeholder {
              color: #9ca3af;
            }
          }
        }

        .el-radio-group {
          .el-radio {
            margin-right: 24px;
            
            :deep(.el-radio__label) {
              color: #374151;
              font-weight: 500;
            }

            &.is-checked {
              :deep(.el-radio__label) {
                color: #3b82f6;
              }
            }
          }
        }

        .el-button {
          border-radius: 8px;
          font-weight: 600;
          padding: 12px 32px;
          font-size: 14px;
          
          &.el-button--primary {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            border: none;
            
            &:hover {
              background: linear-gradient(135deg, #2563eb, #1e40af);
            }
          }
        }
      }
    }
    
    .password-card {
      .el-form {
        .el-form-item {
          margin-bottom: 24px;
        }

        .el-input {
          :deep(.el-input__wrapper) {
            .el-input__suffix {
              .el-input__suffix-inner {
                .el-input__icon {
                  color: #6b7280;
                }
              }
            }
          }
        }

        .el-button {
          &.el-button--danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            border: none;
            
            &:hover {
              background: linear-gradient(135deg, #dc2626, #b91c1c);
            }
          }
        }
      }
      
      .security-tips {
        margin: 0;
        padding-left: 0;
        color: #64748b;
        font-size: 13px;
        line-height: 1.6;
        
        li {
          list-style: none;
          margin-bottom: 6px;
          position: relative;
          padding-left: 16px;

          &::before {
            content: '•';
            color: #3b82f6;
            font-weight: bold;
            position: absolute;
            left: 0;
          }
        }
      }

      .el-alert {
        border-radius: 8px;
        border: 1px solid #bfdbfe;
        background: #eff6ff;
        
        :deep(.el-alert__content) {
          .el-alert__title {
            color: #1e40af;
            font-weight: 600;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .profile-container {
    .profile-content {
      .el-row {
        .el-col {
          &:first-child {
            margin-bottom: 24px;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .profile-container {
    padding: 16px;
    
    .profile-header {
      .header-bg {
        height: 160px;
      }
      
      .user-avatar-section {
        position: static;
        flex-direction: column;
        align-items: center;
        text-align: center;
        padding: 24px;
        background: white;
        border-radius: 0 0 16px 16px;
        margin-top: -20px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        
        .avatar-uploader .avatar-wrapper {
          width: 100px;
          height: 100px;
          border-radius: 12px;
        }

        .user-info {
          margin-bottom: 0;
          
          .username {
            font-size: 24px;
          }
        }
      }
    }
    
    .profile-content {
      margin-top: 24px;

      .el-card {
        :deep(.el-card__header) {
          padding: 20px;
        }

        :deep(.el-card__body) {
          padding: 24px;
        }
      }
    }
  }
}
</style>